<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.rule_id ? $t('编辑') : $t('添加')" append-to-body :v-if="dialogVisible" :visible.sync="dialogVisible" width="500px" top="5vh" @close='close'>
    <div class="dialogContentBoxMaxHeight90">
      <el-form ref="form" :inline="true" :model="record" label-width="130px" :rules="rules" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('协议名称')" class="mqttForm" prop="proto">
          <span style="color:#999;">{{ rule[record.proto] }}</span>
        </el-form-item>
        <el-form-item :label="$t('动作')" class="mqttForm" prop="action">
          <el-select class="mqttLength" v-model="record.action" ref="recordAction" size='small' filterable>
            <el-option v-for="(value, key) in actionList" :key="key" :label="$t(value)" :value="key" :id="`mqtt-action${key}`">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('功能码')" class="mqttForm" prop="msg_type">
          <el-select class="mqttLength" v-model="record.msg_type" ref="msgType" size='small' filterable @change="funcChange">
            <el-option v-for="(value, key) in mqttFUNCList" :key="key" :label="$t(value)" :value="key" :id="`mqtt-msg_type${key}`">
            </el-option>
          </el-select>
        </el-form-item>
        <div v-if="record.msg_type === 'CONNECT'">
          <el-form-item :label="$t('客户端ID')" class="mqttForm" prop="client_id">
            <el-input class="mqttLength" v-model="record.client_id" ref='clientId' size='small' id="mqtt-client_id"> </el-input>
          </el-form-item>
          <el-form-item :label="$t('用户名')" class="mqttForm" prop="usr_name">
            <el-input class="mqttLength" v-model="record.usr_name" ref='userName' size='small' id="mqtt-usr_name"> </el-input>
          </el-form-item>
          <div v-for="(input, index) in record.topic_info" :key="index">
            <el-form-item :label="$t('主题')" class="mqttForm" prop="topic">
              <el-input class="mqttLength" @input="(value)=>handleTopic(value,input)" :value="input.topic" ref='Topic' size='small' filterable :id="`mqtt-topic${index}`">
              </el-input>
            </el-form-item>
          </div>
        </div>
        <div v-if="record.msg_type === 'PUBLISH'">
          <el-form-item :label="$t('主题')" class="mqttForm" prop="topic">
            <div v-for="(input, index) in record.topic_info" :key="index">
              <el-input class="mqttLength" :value="input.topic" @input="(value)=>handleTopic(value,input)" ref='Topic' size='small' filterable :id="`mqtt-PUBLISH-topic${index}`">
              </el-input>
            </div>
          </el-form-item>
        </div>

        <div v-if="record.msg_type === 'SUBSCRIBE'">
          <el-form-item :label="$t('主题')" class="mqttForm" prop="topic">
            <div v-for="(input, index) in record.topic_info" :key="index">
              <el-input class="mqttLength" :value="input.topic" @input="(value)=>handleTopic(value,input)" :placeholder="$t('请输入主题')" ref='Topic' size='small' filterable :id="`mqtt-SUBSCRIBE-topic${index}`">
              </el-input>
            </div>
            <el-tooltip class="mqttForm" effect="dark" :content="$t('新增主题')" placement="top-start">
              <i class="el-icon-plus" @click="addInput" style="margin-left:5px;cursor: pointer;"></i>
            </el-tooltip>
          </el-form-item>

        </div>

        <div v-if="record.msg_type === 'UNSUBSCRIBE'">
          <el-form-item :label="$t('主题')" class="mqttForm" prop="topic">
            <div v-for="(input, index) in record.topic_info" :key="index">
              <el-input class="mqttLength" :value="input.topic" @input="(value)=>handleTopic(value,input)" ref='Topic' size='small' filterable :id="`mqtt-UNSUBSCRIBE-topic${index}`">
              </el-input>
            </div>
            <el-tooltip class="mqttForm" effect="dark" :content="$t('新增主题')" placement="top-start">
              <i class="el-icon-plus" @click="addInput" style="margin-left:5px;cursor: pointer;"></i>
            </el-tooltip>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="innerAddSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="innerAddClose">{{$t('取 消')}}</el-button>
    </span>

  </el-dialog>
</template>
<script>
import ruleArray from '../../ruleArray'
import { selectClass, inputClass } from '@/utils/input-class.js'
// export function 

export default {
  name: 'mqttDialog',
  data () {
  var validateClientId = (rule, value, callback) => {
    if (value !== "") {
      let len = 0;
      for (var i = 0; i < value.length; i++) {
        let c_hex = parseInt(value.charCodeAt(i));
        if (c_hex <= 0x00007f) {
          len += 1; //在UTF-8编码占用1个字节
        } else if (c_hex >= 0x000080 && c_hex <= 0x0007ff) {
          len += 2; //在UTF-8编码中占用2个字节
        } else if (c_hex >= 0x000800 && c_hex <= 0x00ffff) {
          len += 3; //在UTF-8编码中占用3个字节
        } else {
          len += 4;
        }
      }
      if (len > 512) {

        callback(new Error(this.$t('该字段不能超过512个字节')));
      } else {
        callback();
      }
    }
    else
    {
      callback();
    }
  }
  var validateUsrName = (rule, value, callback) => {
    if (value !== "") {
      let len = 0;
      for (var i = 0; i < value.length; i++) {
        let c_hex = parseInt(value.charCodeAt(i));
        if (c_hex <= 0x00007f) {
          len += 1; //在UTF-8编码占用1个字节
        } else if (c_hex >= 0x000080 && c_hex <= 0x0007ff) {
          len += 2; //在UTF-8编码中占用2个字节
        } else if (c_hex >= 0x000800 && c_hex <= 0x00ffff) {
          len += 3; //在UTF-8编码中占用3个字节
        } else {
          len += 4;
        }
      }
      if (len > 512) {
        callback(new Error(this.$t('该字段不能超过512个字节')));
      } else {
        callback();
      }
    }
    else
    {
      callback();
    }
  }
  var validateTopicInfo = (rule, value, callback) => {
    for (let i = 0; i < this.record.topic_info.length; i++) {
        let lastElement = this.record.topic_info[i]
        if (lastElement.topic !== "") {
            let len = 0;
          for (var n = 0; n < lastElement.topic.length; n++) {
            let c_hex = parseInt(lastElement.topic.charCodeAt(n));
            if (c_hex <= 0x00007f) {
              len += 1; //在UTF-8编码占用1个字节
            } else if (c_hex >= 0x000080 && c_hex <= 0x0007ff) {
              len += 2; //在UTF-8编码中占用2个字节
            } else if (c_hex >= 0x000800 && c_hex <= 0x00ffff) {
              len += 3; //在UTF-8编码中占用3个字节
            } else {
              len += 4;
            }
          }
          if (len > 512) {
            callback(new Error(this.$t('该字段不能超过512个字节')));
          }   else {
            callback();
          }
        }
        else
        {
        callback();
        }
        }
  
  }
    return {
      dialogVisible: false,
      record: {
        action: 'accept',
        msg_type: 'CONNECT',
        proto: 'mqtt',
        client_id: '',
        usr_name: '',
        rule_id: null,
        topic_info: [{ topic: '' }],
      },
      recordCopy: {
        action: 'accept',
        msg_type: 'CONNECT',
        proto: 'mqtt',
        client_id: '',
        usr_name: '',
        rule_id: null,
        topic_info: [{ topic: '' }],
      },
      rule: ruleArray.rule,
      mqttFUNCList: ruleArray.mqttFUNCList,
      actionList: { 'accept': '允许', 'alert': '告警' },
      rules: {
        client_id: [{ required: false, validator: validateClientId, trigger: 'blur' }],
        usr_name: [{ required: false, validator: validateUsrName, trigger: 'blur' }],
        topic: [{ required: false, validator: validateTopicInfo, trigger: 'blur' }]
      }
    }
  },
  computed: {
    change () {
      const { msg_type } = this.record
      return { msg_type }
    }
  },
  watch: {
    change (val) {
      if (val.msg_type === 'CONNECT') {
        this.$nextTick(() => { 
          const data = ['clientId', 'userName','Topic']
          inputClass(this.$refs, data)
        })
      }
      else if(val.msg_type === 'PUBLISH') {
        this.$nextTick(() => {
          const data = ['Topic']
          inputClass(this.$refs, data)
        })
      }
      else if(val.msg_type === 'SUBSCRIBE') {
        this.$nextTick(() => {
          const data = ['Topic']
          inputClass(this.$refs, data)
        })
      }
      else if(val.msg_type === 'UNSUBSCRIBE') {
        this.$nextTick(() => {
          const data = ['Topic']
          inputClass(this.$refs, data)
        })
      }
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const selectData = ['recordAction', 'msgType','topic_info', 'usr_name','client_id'] 
        console.log('this.$refs',this.$refs)
        selectClass(this.$refs, selectData)
      })
      if (data) {
        const record = Object.assign(this.record, data)
        this.record = JSON.parse(JSON.stringify(record));
      }
    },
    handleTopic(value,input) {
      console.log(value,value.length)
      input.topic = value.replace(/'/g,'');
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          for (let i = 0; i < this.record.topic_info.length; i++) {
            let lastElement = this.record.topic_info[i]

            if (lastElement.topic !== "") {
              let len = 0;
              for (var n = 0; n < lastElement.topic.length; n++) {
                let c_hex = parseInt(lastElement.topic.charCodeAt(n));
                if (c_hex <= 0x00007f) {
                  len += 1; //在UTF-8编码占用1个字节
                } else if (c_hex >= 0x000080 && c_hex <= 0x0007ff) {
                  len += 2; //在UTF-8编码中占用2个字节
                } else if (c_hex >= 0x000800 && c_hex <= 0x00ffff) {
                  len += 3; //在UTF-8编码中占用3个字节
                } else {
                  len += 4;
                }
              }
              if (len > 512) {
                this.$message({
                  message: this.$t('该字段不能超过512个字节'),
                  type: 'error'
                })
                return;
              }
            } 
          }
          var formData = JSON.parse(JSON.stringify(this.record))
         
          this.$emit('addConfigRuleMap', formData)
        }
      })
    },
    addInput() {
      if(this.record.topic_info.length + 1 > 1000)
      {
        // callback(new Error(this.$t('超出主题最大添加数量，主题最大添加数量为1000个')));
        this.$message({
              message: this.$t('超出主题最大添加数量，主题最大添加数量为1000个'),
              type: 'error'
            })
        return;
      }
      for (let i = 0; i < this.record.topic_info.length; i++) {
        let lastElement = this.record.topic_info[i]

        if (lastElement.topic !== "") {
            let len = 0;
          for (var n = 0; n < lastElement.topic.length; n++) {
            let c_hex = parseInt(lastElement.topic.charCodeAt(n));
            if (c_hex <= 0x00007f) {
              len += 1; //在UTF-8编码占用1个字节
            } else if (c_hex >= 0x000080 && c_hex <= 0x0007ff) {
              len += 2; //在UTF-8编码中占用2个字节
            } else if (c_hex >= 0x000800 && c_hex <= 0x00ffff) {
              len += 3; //在UTF-8编码中占用3个字节
            } else {
              len += 4;
            }
          }
          if (len > 512) {
            this.$message({
              message: this.$t('该字段不能超过512个字节'),
              type: 'error'
            })
            return;
          }
        } 
        }
      this.record.topic_info.push({topic:''});
    },
    funcChange (val) {
      this.record.client_id = ''
      this.record.usr_name = ''
      this.record.topic_info =  [{ topic: '' }]
      },
    close () {
      
      this.dialogVisible = false
      this.$emit('childrenClose')
      if(this.record.rule_id)
      {
        this.$emit('childrenUpdataRule')
      }
      this.record = Object.assign({}, this.recordCopy)

      this.$refs.form.resetFields()
     
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    }
  }
}
</script>
<style>
.mqttLength {
  width: 250px;
}
</style>
